package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type CustomerInfoDao interface {
	GetById(ctx context.Context, id int64) (*model.CustomerInfo, error)
	GetByOpenid(ctx context.Context, openid string) (*model.CustomerInfo, error)
	Create(ctx context.Context, customer *model.CustomerInfo) error
	Update(ctx context.Context, customerInfo *model.CustomerInfo) error
}

func NewCustomerInfoDao(
	r *MysqlClient,
) CustomerInfoDao {
	return &customerInfoDao{
		MysqlClient: r,
	}
}

type customerInfoDao struct {
	*MysqlClient
}

func (r *customerInfoDao) GetById(ctx context.Context, id int64) (*model.CustomerInfo, error) {
	var customerInfo model.CustomerInfo
	if err := r.DB(ctx).Where("id = ?", id).First(&customerInfo).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("customerInfoDao|GetByOpenid(", zap.Any("data", map[string]interface{}{
			"id": id,
		}), zap.Error(err))
		return nil, err
	}
	return &customerInfo, nil
}

func (r *customerInfoDao) GetByOpenid(ctx context.Context, openid string) (*model.CustomerInfo, error) {
	var customer model.CustomerInfo
	if err := r.DB(ctx).Where("wx_open_id = ?", openid).First(&customer).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.Logger().WithContext(ctx).Error("customerInfoDao|GetByOpenid(", zap.Any("data", map[string]interface{}{
			"openid": openid,
		}), zap.Error(err))
		return nil, err
	}
	return &customer, nil
}

func (r *customerInfoDao) Create(ctx context.Context, customerInfo *model.CustomerInfo) error {
	if err := r.DB(ctx).Create(customerInfo).Error; err != nil {
		r.Logger().WithContext(ctx).Error("customerInfoDao|Create(", zap.Any("data", map[string]interface{}{
			"customerInfo": *customerInfo,
		}), zap.Error(err))
		return err
	}
	return nil
}

func (r *customerInfoDao) Update(ctx context.Context, customerInfo *model.CustomerInfo) error {
	if err := r.DB(ctx).Save(customerInfo).Error; err != nil {
		r.Logger().WithContext(ctx).Error("customerInfoDao|Update(", zap.Any("data", map[string]interface{}{
			"customerInfo": *customerInfo,
		}), zap.Error(err))
		return err
	}
	return nil
}
